<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Reply extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'user_id',
        'post_id',
        'parent_id',
        'content',
        'like_count',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'like_count' => 'integer',
    ];

    /**
     * 回复者
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * 所属帖子
     */
    public function post(): BelongsTo
    {
        return $this->belongsTo(Post::class);
    }

    /**
     * 父回复（楼中楼）
     */
    public function parent(): BelongsTo
    {
        return $this->belongsTo(Reply::class, 'parent_id');
    }

    /**
     * 子回复（楼中楼回复）
     */
    public function children(): HasMany
    {
        return $this->hasMany(Reply::class, 'parent_id')->orderBy('created_at', 'asc');
    }

    /**
     * 回复的点赞
     */
    public function likes(): HasMany
    {
        return $this->hasMany(ReplyLike::class);
    }

    /**
     * 判断用户是否已点赞
     */
    public function isLikedBy(?User $user): bool
    {
        if (!$user) {
            return false;
        }

        return $this->likes()->where('user_id', $user->id)->exists();
    }

    /**
     * 判断是否为作者
     */
    public function isAuthor(User $user): bool
    {
        return $this->user_id === $user->id;
    }

    /**
     * 判断是否为楼中楼回复
     */
    public function isNested(): bool
    {
        return $this->parent_id !== null;
    }
}
